var ZPmLat = 47.837778;
var ZPmLon = 35.138333;
var ZOOM = 10;

//Определяем карту, координаты центра и начальный масштаб
var map = L.map('map').setView([ZPmLat, ZPmLon], ZOOM);
//Добавляем на нашу карту слой OpenStreetMap
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a rel="nofollow" href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

//Geo - search
new L.Control.GeoSearch({
    provider: new L.GeoSearch.Provider.OpenStreetMap()
}).addTo(map);

map.on('geosearch_showlocation', function (result) {

		
	alert(result.Location.X + " " + result.Location.Y); 
	
	var target = {"lon" : result.Location.X, "lat": result.Location.Y};
	
	alert(getNearest(target, featureCollections.features));
	//window.location = "near.jsp?lon="+result.Location.X+"&lat="+result.Location.Y;
	//alert(featureCollections.features[0]);
});
//----
// Pop-up for points, style for lines
function onEachFeature(feature, layer) {
    if (feature.geometry&&feature.geometry.type=="Point"){
	    layer.bindPopup(feature.description);
	} else if (feature.type==="LineString"){
			layer.setStyle(lineStyles[feature.style]);
	}
	
	layer.on({
        click: debug
    });
}


//Add all objects on the map
var elements = L.geoJson(featureCollections, {
    onEachFeature: onEachFeature,
	filter: function(feature, layer) { // first loading - always true			
			if (feature.show_on_map){
				return feature.show_on_map;
			}
			else
				return true;
		},
    pointToLayer: function(feature, latlng) {  //Icons for points
        return L.marker(latlng, {icon: L.icon({
			iconUrl: categories[feature.category],
			iconSize: [32, 37],
			iconAnchor: [16, 37],
			popupAnchor: [0, -28]
		})});
    }
});
elements.addTo(map);


// Add list of all points to the select
function listOfThePoints(){
	var points = featureCollections.features;

	points.forEach(function(entry) {
		if(entry.geometry&&entry.geometry.type==="Point"){
        	$('#Obj1').append('<option>' + entry.name + '</option>');
        	$('#Obj2').append('<option>' + entry.name + '</option>');
        }
	});

}

// Add list of all points to select
function listOfLineStyles(){
	
	for (var key in lineStyles) {
	   
		$('#linkStyle').append('<option>' + key + '</option>');
	   // do some more stuff with obj[key]
	}
}

listOfThePoints();
listOfLineStyles();

function debug(e)
{
	var layer = e.target;
	document.getElementById('debug').innerHTML=layer.feature.geometry.type;
}

function clear_elements() {
  map.removeLayer(elements);
}

function draw_elements() {
	elements = L.geoJson(featureCollections, {
		onEachFeature: onEachFeature,
		filter: function(feature, layer) {			
			if ('show_on_map' in feature){
				return feature.show_on_map;
			}
			else
				return true;
		},
		pointToLayer: function(feature, latlng) {  //Icons for points
			return L.marker(latlng, {icon: L.icon({
				iconUrl: categories[feature.category],
				iconSize: [32, 37],
				iconAnchor: [16, 37],
				popupAnchor: [0, -28]
			})});
		}
	});
	
	elements.addTo(map);
}



function getDistance(llon1, llat1, llon2, llat2){
	var rad = 6372795;
	var lat1 = llat1*Math.PI/180;
	var lat2 = llat2*Math.PI/180;
	var lon1 = llon1*Math.PI/180;
	var lon2 = llon2*Math.PI/180;
	
	var delta = lon2 - lon1;
	var cl1 = Math.cos(lat1)
	var cl2 = Math.cos(lat2)
	var sl1 = Math.sin(lat1)
	var sl2 = Math.sin(lat2)
	var cdelta = Math.cos(delta)
	var sdelta = Math.sin(delta)
	
	var y = Math.sqrt(Math.pow(cl2*sdelta,2)+Math.pow(cl1*sl2-sl1*cl2*cdelta,2))
	var x = sl1*sl2+cl1*cl2*cdelta
	var ad = Math.atan2(y,x)
	var dist = ad*rad
	
	return dist;
}

function getInRadius(target, radius, l){
	var result = new Array();
	for (var i = 0; i < l.length; i++){
		if(l[i].geometry&&l[i].geometry.type==="Point"){
			if (getDistance(target.lon, target.lat, l[i].geometry.coordinates[0], l[i].geometry.coordinates[1]) < radius){
				result.push(l[i]);
				l[i].show_on_map = true;
			} else {
				l[i].show_on_map = false;
			}
		}
	}
	
	alert(result.length);
}

function getNearest(target, l){
	var nearest = l[0];
	for (var i = 0; i < l.length; i++){
		if(l[i].geometry&&l[i].geometry.type==="Point"){
			if (getDistance(target.lon, target.lat, l[i].geometry.coordinates[0], l[i].geometry.coordinates[1]) < getDistance(target.lon, target.lat, nearest.geometry.coordinates[0], nearest.geometry.coordinates[1])){
				nearest = l[i];
			}
		}
	}
	return nearest.name;
}

var target = {"lon" : 2, "lat": 2};